<?php

namespace App\Api\SendModule\Controllers;

use App\OrderRecord;
use App\DeliveryRecord;
use Illuminate\Http\Request;
use App\Api\Controllers\BaseController;
use App\Api\GoModule\Controllers\UserPostController;
use Illuminate\Support\Facades\Redis;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use DB;
use Log;

class SendController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
    *@author guyi 824315402@qq.com
    *
    *return the number of cars when user needs to create a order
    *
    *@return $result
    */
    public function carNum(Request $request)
    {
        $query = new UserPostController();
        $result = $query->carNum($request);
        return $result;
    }
    /**
    *return the probable price
    *
    *@param distance
    */
    public function price(Request $request)
    {
        //temp
        $query = new UserPostController();
        $result = $query->price($request);
        return $result;
    }
    /**
    *to save and push order to drivers when the user confirm to create a order
    *
    *
    $@param fromWHo
    *@param fromWhoTel
    *@param from
    *@param fromPosition
    *@param toWho
    *@return json $result about status
    */
    public function orderPush(Request $request)
    {
	
	$token = JWTAuth::getToken();
	$user = JWTAuth::toUser($token);
	$name = $user['nickname'];
        //save userphone in Redis
        $userphone = $user['tel'];
	if(is_null($userphone)) return $this->returnMsg('500','userPhone is null');
	/*
         此处验证订单是否重复提交
         */

	//检测送货订单
	$checkDelis = Redis::sinter('send:'.$userphone);
	if($checkDelis)
	foreach($checkDelis as $orderNum){
		$query = Redis::hgetall($orderNum);
		if($query){
		$isAccept = $query['isAccept'];
		switch($isAccept)	{
	  		case 0:
          		return $this->returnMsg('200', 'ok', ['status'=>'00','orderInfo'=>$query]);
  	 		case 1:
 	  		$driverPhone = $query['driverPhone'];
	  		$driverInfo = $this->getDriverInfo($driverPhone);
              		return $this->returnMsg('200', 'ok', ['status'=>'01','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
  	  		case 2:
 	  		$driverPhone = $query['driverPhone'];
	  		$driverInfo = $this->getDriverInfo($driverPhone);
              		return $this->returnMsg('200', 'ok', ['status'=>'02','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
	  		default:
			break;
			}
		}
		}

	//检测送人订单
	
         $checkredis = Redis::exists('usecar:'.$userphone);
         $check_order_mysql3 = OrderRecord::where('userphone','=',$userphone)->where('isAccept','=',3)->first();
         $check_order_mysql4 = OrderRecord::where('userphone','=',$userphone)->where('isAccept','=',4)->first();
	 
         if($checkredis)//若redis有数据则说明有订单正在进行
         {
                 $query = Redis::hgetall('usecar:'.$userphone);
		 $isAccept = $query['isAccept'];
		 switch($isAccept)	{
	  		case 0:
          		return $this->returnMsg('200', 'ok', ['status'=>'0','orderInfo'=>$query]);
  	 		case 1:
 	  		$driverPhone = $query['driverPhone'];
	  		$driverInfo = $this->getDriverInfo($driverPhone);
              		return $this->returnMsg('200', 'ok', ['status'=>'1','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
  	  		case 2:
 	  		$driverPhone = $query['driverPhone'];
	  		$driverInfo = $this->getDriverInfo($driverPhone);
              		return $this->returnMsg('200', 'ok', ['status'=>'2','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
	  		//case 3:
 	  		  //$driverPhone = $query['driverPhone'];
	  		  //$driverInfo = $this->getDriverInfo($driverPhone);
              		  return $this->returnMsg('200', 'ok', ['status'=>'3','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
			default:
			break;
			}
         }
          if($check_order_mysql3){//未付款
			$driverPhone = $check_order_mysql3->driverPhone;
	  		$driverInfo = $this->getDriverInfo($driverPhone);
              		return $this->returnMsg('200', 'ok', ['status'=>'3','orderInfo'=>$check_order_mysql3,'driverInfo'=>$driverInfo]);
         }
	  if($check_order_mysql4){//未评论
			$driverPhone = $check_order_mysql4->driverPhone;
	  		$driverInfo = $this->getDriverInfo($driverPhone);//dd($driverInfo);
              		return $this->returnMsg('200', 'ok', ['status'=>'4','orderInfo'=>$check_order_mysql4,'driverInfo'=>$driverInfo]);
		}
        	
        $userphone_save = Redis::sadd('userPhone', $userphone);
        //get the sender info
		$from = $request->input('from');
        $fromWho = $request->get('fromWho');
        $fromWhoTel = $request->get('fromWhoTel');
        $fromPosition = $request->get('fromPosition');

		$p_data = explode(',', $fromPosition);//dd($p_data);
        //get the receiver info
        $toWho = $request->get('toWho');
        $toWhoTel = $request->get('toWhoTel');
		$destination = $request->input('destination');//dd($destination);
        $destinationPosition = $request->get('destinationPosition');

        //get the item type
        $type = $request->input('type');
		$weight = $request->get('weight');
		$motoType = $request->input('motoType');

        $isAccept = 0;
		$orderType = 0;//订单类型 0送货
		$time = date('Y-m-d H:i:s', time());
	
		$user_invited = DB::table('wechats')->where('tel','=',$userphone)->select('invited')->first();
		$user_invited = $user_invited->invited;
		$orderNum = time().rand(1000,10000);
        $driverPhones = Redis::sinter('driverPhone');

		$client = stream_socket_client('tcp://120.77.57.178:8888', $errno, $errmsg, 1);
	foreach ($driverPhones as $driverPhone)
	{	
	    $driver = Redis::hgetall('startcar:'.$driverPhone);
	
	    $d_position = $driver['driverPosition'];
	    $isFree = $driver['isFree'];
	    $driver_motoType = $driver['motoType'];
		//如果乘客对车型没要求
		if($motoType==1)
			$motoType = $driver_motoType;
            $d_data = explode(",", $d_position);//dd($d_data);
            $distance = $this->getDistance($p_data[1],$p_data[0],$d_data[1],$d_data[0]);	    
	/***满足经纬度加减0.02(实际距离为4.4公里)的范围的车辆加入推送名单***/    
	if ($distance<=4000 && $isFree==1 ) //isFree==1 表示司机空闲
	 {	
         $data = array(
         'uid'           => $driver,
         'userPhone'     => $userphone,
		 'name'          =>$name,
         'from'          => $from,
		 'fromWho'	 =>$fromWho,
         'toWho'        => $toWho,
         'toWhoTel'     => $toWhoTel,
         'destination'  => $destination,
		 'destinationPosition'=>$destinationPosition,
         'motoType'     => $motoType,
         'created_at'   => $time,
		 'distance'	=>($distance/1000),
		 'orderType'	=>$orderType,
		 'type'		=>$type,
		 'weight'	=>$weight,
		 'orderNum'     =>$orderNum
 		);
		 fwrite($client, json_encode($data)."\n");
        }
	}
        //save in Redis
	$order_data = $this->getPrice($fromPosition,$destinationPosition);
	$price = $order_data['price'];
	$price = round($price,2);//四舍五入到2位小数
	$distance = $order_data['distance'];
	Redis::sadd('send:'.$userphone,$orderNum);
	$query = Redis::hmset(
            $orderNum,
            'name', $name,
	    'from', $from,
	    'fromWho', $fromWho,
            'fromWhoTel', $fromWhoTel,
            'fromPosition', $fromPosition,
            'toWho', $toWho,
            'toWhoTel', $toWhoTel,
            'destination', $destination,
	    'destinationPosition', $destinationPosition,
            'type', $type,
	    'weight', $weight,
            'isAccept', $isAccept,
	    'created_at', $time,
	    'orderType', $orderType,
	    'motoType', $motoType,
  	    'orderNum', $orderNum,
	    'userPhone',$userphone,
	    'price', $price,
	    'distance', $distance,
		'user_invited',$user_invited
        );
        if ($query) {
            $result = $this->returnMsg('200', 'ok', $orderNum);
            return response()->json($result);
        } else {
            $result = $this->returnMsg('56001', 'save order fail');
            return response()->json($result);
        }
    }   


	 public function userCheckOrder(Request $request)
      {
          //get Token
          $token = JWTAuth::getToken();
  
          //get the user infomation
          $user_json = JWTAuth::toUser($token);
  
          $user = json_decode($user_json, true);
          
	  $orderNum = $request->input('orderNum');
	  
	  $query = Redis::hgetall($orderNum);
	if($query){   
	  $status = $query['isAccept'];
	  	switch($status)	{
	  		case 0://无人接单
          		return $this->returnMsg('200', 'ok', ['status'=>'00','orderInfo'=>$query]);
  	 		case 1://司机已接单
 	  		$driverPhone = $query['driverPhone'];
	  		$driverInfo = $this->getDriverInfo($driverPhone);
              		return $this->returnMsg('200', 'ok', ['status'=>'01','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
  	  		case 2://司机正在来
 	  		$driverPhone = $query['driverPhone'];
	  		$driverInfo = $this->getDriverInfo($driverPhone);
              		return $this->returnMsg('200', 'ok', ['status'=>'02','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
  	  		case 3://司机到达，已付款
 	  		$driverPhone = $query['driverPhone'];
	  		$driverInfo = $this->getDriverInfo($driverPhone);
              		return $this->returnMsg('200', 'ok', ['status'=>'03','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
  	  		/*case 4://司机送达，已验收
 	  		$driverPhone = $query['driverPhone'];
	  		$driverInfo = $this->getDriverInfo($driverPhone);
              		return $this->returnMsg('200', 'ok', ['status'=>'04','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
	  		default://没找到订单
	      		return $this->returnMsg('200', 'ok', ['status'=>'-1']);*/
			default:
			break;
			}
		}
	else {
	$checkmysql = DeliveryRecord::where('orderNum',$orderNum)->first();
	$driverPhone = $checkmysql->driverPhone;
	$driverInfo = $this->getDriverInfo($driverPhone);
       	return $this->returnMsg('200', 'ok', ['status'=>'04','orderInfo'=>$checkmysql,'driverInfo'=>$driverInfo]);
	}
	return $this->returnMsg('500','order not found');  
      }


	 public function checkOrderStatus(Request $request)
      {
          //get Token
          $token = JWTAuth::getToken();
  
          //get the user infomation
          $user_json = JWTAuth::toUser($token);
  
          $user = json_decode($user_json, true);
          
	  $orderNum = $request->input('orderNum');
	  
	  $query = Redis::hgetall($orderNum);
	if($query){   
	  $status = $query['isAccept'];
	  	switch($status)	{
	  		case 0://无人接单
          		return $this->returnMsg('200', 'ok', ['status'=>'00']);
  	 		case 1://司机已接单
              		return $this->returnMsg('200', 'ok', ['status'=>'01']);
  	  		case 2://司机正在来
              		return $this->returnMsg('200', 'ok', ['status'=>'02']);
  	  		/*case 3://司机到达，已付款
              		return $this->returnMsg('200', 'ok', ['status'=>'03']);
  	  		case 4://司机送达，已验收
              		return $this->returnMsg('200', 'ok', ['status'=>'04']);*/
	  		default://没找到订单
	      		return $this->returnMsg('200', 'ok', ['status'=>'-1']);
			}
		}
	else return $this->returnMsg('500','order not found');  
      }
    /*
    *@author guyi 824315402@qq.com
    *@desc 根据实际结束行程的位置计算价格
    *@param fromPosition 
    *@param realDestinationPosition
    *@return price
    */
    public function getPrice($fromPosition,$DestinationPosition)
    {
	$key = "bb4894e20165ad23730775378768915a";
	$url = "http://restapi.amap.com/v3/distance?origins=$fromPosition&destination=$DestinationPosition&type=1&key=$key";
  	$ch = curl_init();
 	curl_setopt($ch, CURLOPT_URL, $url);
 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  	curl_setopt($ch, CURLOPT_HEADER, 0);
  	$output = curl_exec($ch);
  	curl_close($ch);
  	$data = json_decode($output,true);
  	$distance = 0;
	//如果高得地图API返回的值是空,按照直线距离
	if($data['status']==1){
			$distance = $data['result']['0']['distance'];
	}else{
	    $p_data = explode(",", $fromPosition);
	    $d_data = explode(",", $DestinationPosition);
            $distance = $this->getDistance($p_data[1],$p_data[0],$d_data[1],$d_data[0]);
	}
	$distance = $distance/1000;
        if ($distance<=3) {
            return ['price'=>5,'distance'=>$distance]; //fiexed没有价格
        } else if( $distance<=8){
            $p = 5+1.5*($distance-3);
            return ['price'=>$p,'distance'=>$distance];
		} 
		else if($distance>8){
			$p = 5+2*($distance-3);
			return ['price'=>$p,'distance'=>$distance];
		}
    }

  
}

